//
//  DR_FileImportTool.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/14.
//

import UIKit
import UniformTypeIdentifiers

class DR_FileImportTool: NSObject {
    
    static let shared = DR_FileImportTool()
    
    // 回调：导入文件后返回文件 URL
    private var completion: ((URL) -> Void)?
    private weak var presentingViewController: UIViewController?
    
    private override init() {
        super.init()
    }
    
    // MARK: - 公开方法：打开文件选择器
    /// 打开文件选择器，支持 PDF、Word、Excel、PPT
    /// - Parameters:
    ///   - viewController: 用于展示文件选择器的 ViewController
    ///   - completion: 选择完成后的回调，返回导入的文件 URL
    func presentDocumentPicker(from viewController: UIViewController, completion: @escaping (URL) -> Void) {
        self.presentingViewController = viewController
        self.completion = completion
        
        presentDocumentPicker()
    }
    
    // MARK: - 打开文件选择器
    private func presentDocumentPicker() {
        guard let viewController = presentingViewController else {
            print("⚠️ [DR_FileImportTool] 无法获取 ViewController")
            return
        }
        
        var documentTypes: [String] = []
        
        if #available(iOS 14.0, *) {
            // iOS 14+ 使用 UTType
            var types: [UTType] = [.pdf]
            
            // Word 文档类型
            if let wordDoc = UTType(filenameExtension: "doc") {
                types.append(wordDoc)
            }
            if let wordDocx = UTType(filenameExtension: "docx") {
                types.append(wordDocx)
            }
            
            // Excel 文档类型
            if let excelXls = UTType(filenameExtension: "xls") {
                types.append(excelXls)
            }
            if let excelXlsx = UTType(filenameExtension: "xlsx") {
                types.append(excelXlsx)
            }
            
            // PPT 文档类型
            if let ppt = UTType(filenameExtension: "ppt") {
                types.append(ppt)
            }
            if let pptx = UTType(filenameExtension: "pptx") {
                types.append(pptx)
            }
            
            documentTypes = types.map { $0.identifier }
        } else {
            // iOS 13 及以下使用 UTI
            documentTypes = [
                "com.adobe.pdf",                                    // PDF
                "com.microsoft.word.doc",                            // Word .doc
                "org.openxmlformats.wordprocessingml.document",      // Word .docx
                "com.microsoft.excel.xls",                           // Excel .xls
                "org.openxmlformats.spreadsheetml.sheet",            // Excel .xlsx
                "com.microsoft.powerpoint.ppt",                      // PPT .ppt
                "org.openxmlformats.presentationml.presentation"     // PPT .pptx
            ]
        }
        
        let documentPicker = UIDocumentPickerViewController(documentTypes: documentTypes, in: .import)
        documentPicker.delegate = self
        documentPicker.allowsMultipleSelection = false
        documentPicker.modalPresentationStyle = .formSheet
        
        viewController.present(documentPicker, animated: true)
    }
    
    // MARK: - 处理选中的文件
    private func handleSelectedFile(_ fileURL: URL) {
        // 获取文件扩展名
        let fileExtension = fileURL.pathExtension.lowercased()
        
        // 确定文件类型和保存目录
        let (fileType, saveDirectory) = getFileTypeAndDirectory(for: fileExtension)
        
        guard let saveDirectory = saveDirectory else {
            print("⚠️ [DR_FileImportTool] 不支持的文件类型: \(fileExtension)")
            completion?(fileURL) // 即使不支持，也返回原始 URL
            completion = nil
            presentingViewController = nil
            return
        }
        
        // 确保保存目录存在
        if !FileManager.default.fileExists(atPath: saveDirectory.path) {
            try? FileManager.default.createDirectory(at: saveDirectory, withIntermediateDirectories: true, attributes: nil)
        }
        
        // 生成目标文件路径
        let fileName = fileURL.lastPathComponent
        let destinationURL = saveDirectory.appendingPathComponent(fileName)
        
        // 如果文件已存在，添加时间戳后缀
        let finalURL = ensureUniqueFileName(destinationURL)
        
        // 复制文件到目标目录
        do {
            // 获取文件访问权限
            guard fileURL.startAccessingSecurityScopedResource() else {
                print("⚠️ [DR_FileImportTool] 无法访问文件: \(fileURL.path)")
                completion?(fileURL)
                completion = nil
                presentingViewController = nil
                return
            }
            defer {
                fileURL.stopAccessingSecurityScopedResource()
            }
            
            // 复制文件
            try FileManager.default.copyItem(at: fileURL, to: finalURL)
            print("✅ [DR_FileImportTool] 文件导入成功: \(finalURL.path)")
            
            completion?(finalURL)
        } catch {
            print("❌ [DR_FileImportTool] 文件导入失败: \(error.localizedDescription)")
            completion?(fileURL) // 失败时返回原始 URL
        }
        
        // 清空回调
        completion = nil
        presentingViewController = nil
    }
    
    // MARK: - 获取文件类型和保存目录
    private func getFileTypeAndDirectory(for fileExtension: String) -> (String, URL?) {
        let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        
        switch fileExtension {
        case "pdf":
            let pdfPath = documentsPath.appendingPathComponent("PDFs", isDirectory: true)
            return ("PDF", pdfPath)
        case "doc", "docx":
            let wordPath = documentsPath.appendingPathComponent("Word", isDirectory: true)
            return ("Word", wordPath)
        case "xls", "xlsx":
            let excelPath = documentsPath.appendingPathComponent("Excel", isDirectory: true)
            return ("Excel", excelPath)
        case "ppt", "pptx":
            let pptPath = documentsPath.appendingPathComponent("PPT", isDirectory: true)
            return ("PPT", pptPath)
        default:
            return ("Unknown", nil)
        }
    }
    
    // MARK: - 确保文件名唯一
    private func ensureUniqueFileName(_ url: URL) -> URL {
        var finalURL = url
        var counter = 1
        
        while FileManager.default.fileExists(atPath: finalURL.path) {
            let fileName = url.deletingPathExtension().lastPathComponent
            let fileExtension = url.pathExtension
            let newFileName = "\(fileName)_\(counter).\(fileExtension)"
            finalURL = url.deletingLastPathComponent().appendingPathComponent(newFileName)
            counter += 1
        }
        
        return finalURL
    }
}

// MARK: - UIDocumentPickerDelegate
extension DR_FileImportTool: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let fileURL = urls.first else {
            completion = nil
            presentingViewController = nil
            return
        }
        
        handleSelectedFile(fileURL)
    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        // 用户取消选择
        completion = nil
        presentingViewController = nil
    }
}

